import { CacheTree } from "bdjf_http";
import { BdjfRequest } from "../type";


export function getCacheKey(cacheRequest:BdjfRequest):CacheTree|string{
    const bindCacheKey = cacheRequest.cacheOption?.bindCacheKey;
    if (bindCacheKey) {
        // data 一般为post中传输数据
        // params 一般为 get 中传输数据
        const params = cacheRequest.requestOption.data||cacheRequest.requestOption.params;
        if(bindCacheKey === 'all'){
            const keys = Object.keys(params);

            const cacheKeys = filterExcludeCacheKey(keys,cacheRequest.cacheOption!.excludeCacheKey!);

            return generateKeyByCacheKeys(params, cacheKeys);

        }else if(bindCacheKey.length > 0){

            const cacheKeys = filterExcludeCacheKey(bindCacheKey,cacheRequest.cacheOption!.excludeCacheKey);

            return generateKeyByCacheKeys(params, cacheKeys);
        }
    } 

    return cacheRequest.requestOption.url;
}

// 排除掉反选的
function filterExcludeCacheKey (keys:string[],excludes?:string[]){
    if(!excludes||excludes.length === 0){
        return keys;
    }
    return keys.filter(key=>{
        return excludes.indexOf(key)<0;
    })
}

// 根据key数组生成树
function generateKeyByCacheKeys (params: any,keyIndexArr: string[]){
    // params 不是对象时报错
    if(Object.prototype.toString.call(params) !== '[object Object]'){
        throw new Error(`bdjf-error:params(${params}) must be a object,when you use catch`);
    }
    const key: CacheTree = {};
    for(const i in keyIndexArr){
        const index: string = keyIndexArr[i];
        key[index] = params[index];
    }
    return key;
}